package edu.hgnc.controller.initBinder;

import edu.hgnc.bean.Student;
import edu.hgnc.bean.User;
import edu.hgnc.controller.DemoController;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


/**
 * InitBinder 注解作用于Controller中的方法，表示为当前控制器注册一个属性编辑器
 * 对webDataBinder进行初始化且只读当前的Controller有效
 */
@Controller
public class InitBinderController {

	private static final Log logger = LogFactory.getLog(DemoController.class);

	@RequestMapping("/param")
	public String getFormatDate(Date date, Map<String,Object> map){
		logger.debug("date"+date);
		map.put("name","xiaoMing");
		map.put("age",18);
		map.put("date",date);
		return "map";
	}

	@InitBinder
	public void initBinder(WebDataBinder binder){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		CustomDateEditor editor = new CustomDateEditor(format, true);
		// 通过binder注册自定义的属性编辑器
		binder.registerCustomEditor(Date.class,editor);
	}

	@InitBinder("user")
	public void init1(WebDataBinder binder){
		binder.setFieldDefaultPrefix("u.");
	}

	@InitBinder("stu")
	public void init2(WebDataBinder binder){
		binder.setFieldDefaultPrefix("s.");
	}

	@RequestMapping("/getBean")
	public ModelAndView getObj(User user, @ModelAttribute("stu") Student stu){
		logger.debug("stu"+stu);
		return null;
	}
}
